"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   :  触发SIGBUS信号量，检查是否走UCE检测
Create At   : 2021/05/11
@zou_jialiang0505328126
Description :
    1. 触发SIGBUS
Expect      :
    1.数据库停止，不存在残留线程，pg_log中无对应记录,ffic中有记录
History     :
    Modified by @wan005:修改用例编号
    Modified by @wan005 2021/07/06:修改log查询方式，规避测试环境时间跳转问题
    Modified by @wan005 2021/07/06:修改log查询方式
    Modified by @wan005 2021/10/14:适配最新代码，数据库异常停止后集群状态为unavailable
    Modified by @wan005 2021/11/1:增加等待延迟，并再确保ffic文件写入后再查询pg_log
    Modified by @wan005 2022/3/18:3.0.0版本删除UCE特性
"""


import unittest
import time
import os
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster


class Uceclass(unittest.TestCase):
    db_primary_user_node = Node(node='PrimaryDbUser')
    db_primary_root_node = Node(node='PrimaryRoot')
    logger = Logger()
    common = Common()
    commonsh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.logger.info("-----------this is setup-----------")
        self.logger.info('--Opengauss_Reliability_OS_UCE_Case012.py start--')
        self.pg_log = os.path.join(
            macro.PG_LOG_PATH, macro.DN_NODE_NAME.split('/')[0])
        self.ffic_log = os.path.join(os.path.dirname(macro.PG_LOG_PATH),
                                     'ffic_log')

    def test_stop_immediate(self):
        cmd = f"ls -al {self.ffic_log}|  grep \"^-\" | wc -l"
        ffic_before = self.db_primary_user_node.sh(cmd).result()
        self.logger.info(ffic_before)

        text = "--step1:触发SIGBUS  expect:数据库停止，" \
               "不存在残留线程，pg_log中无对应记录,ffic中有记录--"
        self.logger.info(text)
        self.logger.info('-----------kill -7------------------')
        self.common.kill_pid(self.db_primary_root_node, '7')
        time.sleep(30)
        cmd = f"ls -al {self.ffic_log}|  grep \"^-\" | wc -l"
        ffic_after = self.db_primary_user_node.sh(cmd).result()
        self.logger.info(ffic_after)
        result = self.commonsh.getDbClusterStatus('detail')
        self.assertIn("Unavailable", result)
        time.sleep(30)

        self.logger.info('--------------check pg_log-----------------')
        for i in range(4):
            if int(ffic_after) <= int(ffic_before):
                time.sleep(10)
            else:
                break
        cmd = f'find {self.pg_log} -iname "post*" -mmin -2 | xargs ls -lta'
        self.logger.info(cmd)
        result = self.db_primary_root_node.sh(cmd).result()
        self.logger.info(result)
        self.current_log = result.splitlines()[0].split(" ")[-1]
        cmd = f'cat {self.current_log} | grep "SIGBUS signal received"'
        self.logger.info(cmd)
        result = self.db_primary_root_node.sh(cmd).result()
        self.logger.info(result)
        self.assertNotIn('SIGBUS signal received', result,
                         "执行失败：" + text)
        cmd = f'find {self.ffic_log} -iname "ffic_gaussdb*" ' \
            f'-mmin -2 | xargs ls -lta'
        self.logger.info(cmd)
        result = self.db_primary_root_node.sh(cmd).result()
        self.logger.info(result)
        self.current_log = result.splitlines()[0].split(" ")[-1]
        cmd = f'cat {self.current_log} | grep "SIGBUS"'
        self.logger.info(cmd)
        result = self.db_primary_root_node.sh(cmd).result()
        self.logger.info(result)
        self.assertIn('SIGBUS', result, "执行失败：" + text)

    def tearDown(self):
        self.logger.info('----------this is tearDown---------')
        self.logger.info('restart database')
        self.commonsh.startDbCluster()
        self.logger.info('--Opengauss_Reliability_OS_UCE_Case012.py end--')
